package com.mjk.common.web.getway.restful.prototal.websocket.impl;


import com.mjk.common.tools.logger.BizLogger;
import com.mjk.common.web.getway.constns.GetwayConsts;
import com.mjk.common.web.getway.restful.interceptor.GetWayInterceptorReq;
import com.mjk.common.web.getway.restful.prototal.websocket.impl.instance.WebSocketInstance;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;


import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 前后端交互的类实现消息的接收推送(自己发送给自己)
 *请求地址为 ws://localhost:18092/test/one
 * @ServerEndpoint(value = "/test/one") 前端通过此URI和后端交互，建立连接
 */
@ServerEndpoint(value = "/ws/{prototal}/{version}/{work}")
@Component
public class WebSocketServer {

    /** 记录当前在线连接数 */
    private static final AtomicInteger onlineCount = new AtomicInteger(0);
    
    /**		
     *  存放每个客户端对应的websocket对象
     */
    private static final ConcurrentHashMap<String, WebSocketInstance> webSocketMap = new ConcurrentHashMap<>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("prototal")String prototal, @PathParam("version") String version, @PathParam("work")String work, Session session) {
    	Map<String,Object> restfulParams = new HashMap<>();
        restfulParams.put(GetwayConsts.PROTOCOL, prototal);
        restfulParams.put(GetwayConsts.VERSION, version);
        restfulParams.put(GetwayConsts.INSTANCE	, work);
        GetWayInterceptorReq req = new GetWayInterceptorReq();
        req.setRestfulParams(restfulParams);
    
        WebSocketInstance service ;
        if(webSocketMap.containsKey(session.getId())) {
        	service = webSocketMap.get(session.getId());
        }else {
        	service = new WebSocketInstance(session, req);
        	onlineCount.incrementAndGet(); // 在线数加1
        }
    	webSocketMap.put(session.getId(), service);
        BizLogger.info("有新连接加入："+session.getId()+"，当前在线人数为："+onlineCount.get());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
    	 if(webSocketMap.containsKey(session.getId())) {
    		webSocketMap.remove(session.getId());
    		onlineCount.decrementAndGet(); // 在线数减1
    	 }
    	 BizLogger.info("有一连接关闭："+session.getId()+"，当前在线人数为："+onlineCount.get());
    }
    /**
     * 给所有连接发送
     * @param message
     */
    @OnMessage
    public void onMessage(String message,Session session) {
    	if(!CollectionUtils.isEmpty(webSocketMap)) {
    		WebSocketInstance server = webSocketMap.get(session.getId());
    		//组装参数 发送到拦截链     		
    		server.sendMessage(message);
    	}
    }

    @OnError
    public void onError(Session session, Throwable error) {
        BizLogger.error("发生错误");
        BizLogger.error(error);
    }
}